package io.itit.ecp.admin.provide.action.controller.miniprogram;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.provide.action.req.InternetElectricityPriceQueryReq;
import io.itit.ecp.admin.provide.action.resp.InternetElectricityPriceResp;
import io.itit.ecp.admin.server.entity.InternetElectricityPriceEntity;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Objects;

/**
 * 上网电价控制类
 */
@Api(tags = "上网电价管理")
@RestController
@RequestMapping("/mini/internetElectricityPrice")
public class MiniInternetElectricityPriceController {

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    public ResultResp<IPage<InternetElectricityPriceResp>> queryPage(@RequestBody @Validated(IQueryPage.class) InternetElectricityPriceQueryReq req) {
        Page<InternetElectricityPriceResp> page = buildQW(req).joinPage(PageUtils.getPage(req, InternetElectricityPriceResp.class), InternetElectricityPriceResp.class);
        return ResultResp.success(page);
    }

    private static JoinLambdaWrapper<InternetElectricityPriceEntity> buildQW(InternetElectricityPriceQueryReq req) {
        LocalDateTime start = Objects.nonNull(req.getTime()) ? req.getTime().atTime(LocalTime.MIN) : null;
        return Joins.of(InternetElectricityPriceEntity.class)
                .eq(StringUtils.hasLength(req.getSceneProjectId()), InternetElectricityPriceEntity::getSceneProjectId, req.getSceneProjectId())
                .ge(Objects.nonNull(start), InternetElectricityPriceEntity::getStartTime, start)
                .orderByDesc(StringUtils.hasLength(req.getSortColumn()), InternetElectricityPriceEntity::getCreateTm);
    }
}
